import ajax from "../Ajax";

const path = require('path')

let unloadImgUrl = 'https://pics.images.ac.cn/image/5f1e7f2d2c987.html'

let userDefaultImgUrl = 'https://pics.images.ac.cn/image/5f1e988811b02.html'

let regex = {
    phone: /^1[3456789]\d{9}$/,
    email: /^([a-zA-Z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
    idCard: /^[1-9]\d{5}(18|19|([2-3]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
    qq: /^[1-9][0-9]{4,10}$/,
    weChat: /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/
}

const getParseUrl = () => {
    var url = location.search, //获取url中"?"符后的字串
        theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

const apiUrl = (url) => {
    return `https://localhost:8080/${url}`
}

const setLocalStorage = (k, v) => {
    localStorage.setItem(k, v)
}

const getLocalStorage = (k) => {
    return localStorage.getItem(k)
}

const clearLocalStorage = (k) => {
    if (k) {
        localStorage.removeItem(k);
    } else {
        localStorage.clear();
    }
}

const setSessionStorage = (k, v) => {
    sessionStorage.setItem(k, v);
}

const getSessionStorage = (k) => {
    return sessionStorage.getItem(k)
}
const clearSessionStorage = (k) => {
    if (k) {
        sessionStorage.removeItem(k);
    } else {
        sessionStorage.clear();
    }
}

//设置cookie
const setCookie = (cname, cvalue, exdays) => {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

//获取cookie
const getCookie = (name) => {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

//移除cookie
const removeCookie = (name) => {
    document.cookie = name + '=""';
}
/**
 * 时间戳转换日期
 * @param {*} t
 */
const dateTimeFormat = (t, model) => {
    var format = function(str) {
        if (parseInt(str) < 10) {
            return "0" + str;
        } else {
            return str;
        }
    };

    var now = new Date(t),
        year = now.getFullYear(),
        month = now.getMonth() + 1,
        date = now.getDate(),
        hour = now.getHours(),
        minute = now.getMinutes(),
        second = now.getSeconds();
    if (model) {
        return `${year}-${format(month)}-${format(date)} ${format(hour)}:${format(minute)}:${format(second)}`;
    } else {
        return `${year}-${format(month)}-${format(date)}`;

    }

}

/**
 * 图片上传
 * @param {*} eObj
 * @param {*} max
 * @param {*} callback
 */
const uploadPics = (eObj, max, callback) => {
    let pic = [];
    let size = 2 * 1024 * 1024;
    let param = new FormData();
    let files = eObj.target.files || eObj.dataTransfer.files;
    if (!files.length) return;
    if (typeof FileReader === 'undefined') {
        alert('您的浏览器不支持图片上传，请升级您的浏览器');
        return false;
    }

    let len = files.length;
    for (let i = 0; i < len; i++) {
        pic.push(files[i]);
    }
    if  (pic.length  >  max) {
        alert(`最多只能上传${max}张`);
        return  false;
    }
    for (let i = 0, ii = pic.length; i < ii; i++) {
        if (files[i].size > size) {
            alert(`第${i + 1}张图片大于2M，请重新选择图片`);
            return false;
        } else {
            param.append("file", pic[i]);
            uploadPicsRequest(param, res => {
                callback(res);
            });
        }
    }
}


const uploadPic = (eObj, callback) => {
    let size = 2 * 1024 * 1024;
    let param = new FormData();
    let files = eObj.target.files || eObj.dataTransfer.files;
    if (!files.length) return;
    if (typeof FileReader === 'undefined') {
        alert('您的浏览器不支持图片上传，请升级您的浏览器');
        return false;
    }
    if (files[0].size > size) {
        alert("图片大于2M，请重新选择图片");
        return false;
    } else {
        param.append("file", files[0]);
        uploadPicsRequest(param, res => {
            callback(res);
        });
    }

}

const uploadFile = (eObj, callback) => {
    let size = 5 * 1024 * 1024;
    let param = new FormData();
    let files = eObj.target.files || eObj.dataTransfer.files;
    if (!files.length) return;
    if (typeof FileReader === 'undefined') {
        alert('您的浏览器不支持文件上传，请升级您的浏览器');
        return false;
    }
    if (files[0].size > size) {
        alert("文件大于5M，请重新选择文件");
        return false;
    } else {
        param.append("file", files[0]);
        param.append("type", "policy");
        uploadFileRequest(param, res => {
            callback(res);
        });
    }
}


const uploadPicsRequest = (data, callback) => {
    ajax.post('api1/public/upload_img_oss', data).then(res => {
        callback(res.data)
    })
}
const uploadFileRequest = (data, callback) => {
    ajax.post('api1/public/upload_file_oss', data).then(res => {
        callback(res.data)
    })
}

export default {
    unloadImgUrl,
    userDefaultImgUrl,
    regex,
    getParseUrl,
    apiUrl,
    setLocalStorage,
    getLocalStorage,
    clearLocalStorage,
    setSessionStorage,
    getSessionStorage,
    clearSessionStorage,
    setCookie,
    getCookie,
    removeCookie,
    dateTimeFormat,
    uploadPics,
    uploadPic,
    uploadFile,
    uploadPicsRequest,
    uploadFileRequest
}
